import wx
import cubudget
import features.interest
import features.HealthCheck
import features.report
from xml.parsers.expat import ExpatError
from AccountWin import AccountWin
class MainWindow(wx.App):
    __module__ = __name__

    def OnInit(self):
        self.AccountWindow = None
        wx.InitAllImageHandlers()
        self.AccountWindow = AccountWin(None, -1, '')
        self.curDate = self.AccountWindow.dpcDate.GetValue()
        self.SetTopWindow(self.AccountWindow)
        self.AccountWindow.txtAmount.Value = '0.00'
        self.AccountWindow.intCurrentItemNumber = 0
        self.AccountWindow.txtCheckNumber.Enabled = False
        self.AccountWindow.TransactionEntries.InsertColumn(0, 'Date')
        self.AccountWindow.TransactionEntries.InsertColumn(1, 'Source', width=100)
        self.AccountWindow.TransactionEntries.InsertColumn(2, 'Destination', width=100)
        self.AccountWindow.TransactionEntries.InsertColumn(3, 'Debit')
        self.AccountWindow.TransactionEntries.InsertColumn(4, 'Credit')
        self.AccountWindow.TransactionEntries.InsertColumn(5, 'Balance')
        self.AccountWindow.TransactionEntries.InsertColumn(6, 'Comment', width=280)
        self.AccountWindow.core = cubudget.Core()
        self.AccountWindow.Bind(wx.EVT_BUTTON, self.OnClear, self.AccountWindow.button_1)
        self.AccountWindow.Bind(wx.EVT_BUTTON, self.OnDelete, self.AccountWindow.button_2)
        self.AccountWindow.Bind(wx.EVT_BUTTON, self.OnEnter, self.AccountWindow.button_3)
        self.AccountWindow.Show()
        return True



    def OnClear(self, event):
        self.AccountWindow.dpcDate.SetValue(self.curDate)
        self.AccountWindow.txtSource.Value = ''
        self.AccountWindow.txtComment.Value = ''
        self.AccountWindow.txtDestination.Value = ''
        self.AccountWindow.txtCheckNumber.Value = ''
        self.AccountWindow.txtAmount.Value = '0.00'
        self.AccountWindow.intCurrentItemNumber = -1
        self.AccountWindow.TypeBox.SetSelection(0)
        self.AccountWindow.txtCheckNumber.Enabled = False



    def OnEnter(self, event):
        amt = self.AccountWindow.txtAmount.Value
        checkNum = self.AccountWindow.txtCheckNumber.Value
        source = self.AccountWindow.txtSource.Value
        try:
            amt = float(amt)
        except ValueError:
            wx.MessageBox('Amount is not numeric')
            return None
        checkTest = str((checkNum.isdigit() or (not checkNum)))
        if (checkTest == 'False'):
            wx.MessageBox('Check# is not numeric')
            return None
        if (self.AccountWindow.txtSource.Value == ''):
            wx.MessageBox('Please input a Source')
            return None
        if (self.AccountWindow.txtDestination.Value == ''):
            wx.MessageBox('Please input a Destination')
            return None
        date = wx.DateTime.Format(self.AccountWindow.dpcDate.GetValue(), '%m/%d/%Y')
        self.AccountWindow.TransactionEntries.InsertStringItem(self.AccountWindow.intCurrentItemNumber, date)
        self.AccountWindow.TransactionEntries.SetStringItem(self.AccountWindow.intCurrentItemNumber, 1, source)
        self.AccountWindow.intCurrentItemNumber += 1
        newTrans = cubudget.Transaction(destinationAccount=self.AccountWindow.txtDestination, sourceAccount=self.AccountWindow.txtSource.Value, amount=amt, date=date, notes=checkNum)
        if (self.AccountWindow.core.getAllAccounts() == None):
            wx.MessageBox('Please create an account')
            print 'Launch account creation dialog here...'
            return None
        self.AccountWindow.core.addTransaction(newTrans)



    def OnDelete(self, event):
        try:
            self.AccountWindow.TransactionEntries.DeleteItem(AccountWindow.intCurrentItem)
        except:
            print 'Cannot delete'
            return None



    def newFileOverride(self, event):
        print "Event handler `newFile' not implemented!"
        event.Skip()



    def openFileOverride(self, event):
        if (self.core.checkDirty() == 1):
            self.promptForSave()
        dlg = wx.FileDialog(self, wildcard='*.xml', style=wx.OPEN)
        if dlg.ShowModal():
            path = dlg.GetPath()
            if (path != ''):
                retCode = self.core.loadFile(path)
                if (retCode is IOError):
                    dlg = wx.MessageDialog(None, 'Error opening file', 'Error', (wx.OK | wx.ICON_ERROR))
                    dlg.ShowModal()
                if (retCode is ExpatError):
                    dlg = wx.MessageDialog(None, 'Invalid XML File', 'Error', (wx.OK | wx.ICON_ERROR))
                    dlg.ShowModal()



    def saveFileOverride(self, event):
        dlg = wx.FileDialog(self, wildcard='*.xml', style=wx.SAVE)
        if dlg.ShowModal():
            path = dlg.GetPath()
            if (path != ''):
                retCode = self.core.saveFile(path)
                if (retCode is IOError):
                    dlg = wx.MessageDialog(None, 'Error saving file', 'Error', (wx.OK | wx.ICON_ERROR))
                    dlg.ShowModal()



    def exportFileOverride(self, event):
        self.report = features.report.Report()
        self.report.makeReport(self.core.getAllAccounts())



    def closeFileOverride(self, event):
        print "Event handler `closeFile' not implemented!"
        event.Skip()



    def exitOverride(self, event):
        if (self.core.checkDirty() == 1):
            self.promptForSave()
        exit()



    def interestRunnerOverride(self, event):
        self.interest.interest_runner(self.core.getAllAccounts())



    def healthCheckOverride(self, event):
        print "Event handler `healthCheck' not implemented!"
        event.Skip()



    def aboutOverride(self, event):
        wx.MessageBox('See Doc Dir. Good Luck')



    def promptForSave(self):
        dlg = wx.MessageDialog(self, 'Would you like to save the changes you have made?', 'Save changes?', (wx.ICON_QUESTION | wx.YES_NO))
        if (dlg.ShowModal() == wx.ID_YES):
            self.OnMenuFileSaveMenu(self)


    AccountWin.newFile = newFileOverride
    AccountWin.openFile = openFileOverride
    AccountWin.saveFile = saveFileOverride
    AccountWin.exportFile = exportFileOverride
    AccountWin.closeFile = closeFileOverride
    AccountWin.exit = exitOverride
    AccountWin.healthCheck = healthCheckOverride
    AccountWin.interestRunner = interestRunnerOverride
    AccountWin.about = aboutOverride


def main():
    application = MainWindow(0)
    application.MainLoop()


if (__name__ == '__main__'):
    main()

